<template>
  <div>
    <SectionTitle title="申请信息" style="margin-bottom: 16px;" />
    <el-form
      ref="applicationInfoForm"
      :rules="rules"
      :model="applicationInfo"
      :label-width="showMobilePage ? '80px' : '130px'"
      :label-position="showMobilePage ? 'left' : 'right'"
      class="lineHeight32">
      <el-row class="response-el-row" type="flex">
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="引用历史" prop="referenceApprovalNo">
            <el-input
              ref="customInputRef"
              v-model="applicationInfo.referenceApprovalNo"
              placeholder="请选择"
              class="custom-input"
              name="referenceApprovalNo"
              type="text"
              @focus="onHistoryInvoiceDrawerShow">
              <i slot="suffix" class="el-icon-arrow-down custom-input-icon" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="申请人" prop="proposerId">
            <selectWithUserLoad
              v-model="applicationInfo.proposerId"
              :default-list="defaultProposer"
              :show-check-user="true"
              filterable
              collapse-tags
              clearable
              placeholder="请选择申请人"
              @changeMethod="handleProposerChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="申请部门" prop="applyDepartmentId">
            <el-cascader
              v-model="applicationInfo.applyDepartmentId"
              :show-all-levels="false"
              :options="deptList"
              :props="{
                emitPath:false,
                value: 'id',
                label: 'name',
                checkStrictly: true,
                multiple: false,
              }"
              placeholder="请选择所属部门"
              size="small"
              collapse-tags
              filterable
              clearable>
              <template slot-scope="{ data }">
                <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                  <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                  <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                </el-tooltip>
                <span v-else>{{ data.name || '--' }}</span>
              </template>
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="我方抬头" prop="ourTitle">
            <el-select
              v-model="applicationInfo.ourTitle"
              name="ourTitle"
              placeholder="发票抬头"
              popper-class="global-select-down panel-auto-width"
              @change="changeOurTitle">
              <el-option
                v-for="item in ourTitleList"
                :key="item.id"
                :label="item.label"
                :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="发票类型" prop="invoiceType">
            <el-select
              v-model="applicationInfo.invoiceType"
              :no-data-text="applicationInfo.ourTitle?'无数据' : '请先选择我方抬头'"
              name="invoiceType"
              popper-class="global-select-down"
              @change="changeInvoiceType">
              <el-option
                v-for="item in invoiceTypes"
                :key="item.id"
                :label="item.name"
                :value="item.name" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="开票项目" prop="project">
            <el-select
              v-model="applicationInfo.project"
              name="project"
              popper-class="global-select-down">
              <el-option
                v-for="item in invoiceProjectList"
                :key="item.id"
                :label="item.label"
                :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="含税金额(元)" prop="amount">
            <div class="flex-center">
              <el-input
                v-model="applicationInfo.amount"
                placeholder="请输入含税金额"
                name="amount"
                type="text"
                maxlength="15"
                oninput="if(value>999999999)value=999999999"
                @input="numInputChange($event, 'amount')"
              />
              <el-tooltip :open-delay="800" placement="top" effect="dark">
                <div slot="content" style="max-width: 210px">
                  <span>开负数发票，请备注说明情况：</span><br>
                  <span>1. 已知原正数发票的情况：提供【正数发票】，一张正数发票对应一张负数发票，在备注填写发票号码</span><br>
                  <span>2. 未知正数发票的情况：提供【红字信息表】，一张红字信息表对应一张负数发票</span>
                </div>
                <tipIcon is-diy style="position:relative;top:2px;margin-left:6px;"/>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="是否到账" prop="isArrival">
            <el-radio-group v-model="applicationInfo.isArrival">
              <el-radio :label="1"><span style="font-size:14px;">是</span></el-radio>
              <el-radio :label="0"><span style="font-size:14px;">否</span></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="applicationInfo.isArrival === 0" :span="12" class="responsive-col-lg-8">
          <el-form-item label="合约付款日" prop="arrivalDate">
            <el-date-picker
              v-model="applicationInfo.arrivalDate"
              :editable="false"
              type="date"
              placeholder="请选择"
              value-format="timestamp"
              format="yyyy/MM/dd"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="合同签订" prop="isSign">
            <el-radio-group v-model="applicationInfo.isSign">
              <el-radio :label="1"><span style="font-size:14px;">已签订</span></el-radio>
              <el-radio :label="0"><span style="font-size:14px;">未签订</span></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="发票接收邮箱" prop="email">
            <el-input
              v-model="applicationInfo.email"
              placeholder="请输入发票接收邮箱"
              name="email"
              type="text"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="业务类型" prop="applyBusinessType">
            <el-select
              v-model="applicationInfo.applyBusinessType"
              name="applyBusinessType"
              popper-class="global-select-down">
              <el-option
                v-for="item in applyBusinessTypes"
                :key="item.value"
                :value="item.value"
                :label="item.label">
                <span v-if="!item.tip">{{ item.label }}</span>
                <el-tooltip v-else placement="top">
                  <div slot="content">{{ item.tip }}</div>
                  <span>{{ item.label }}</span>
                </el-tooltip>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="附件" prop="attachment">
            <upAttachment
              ref="uploadAttachment"
              :hide-confirm="true"
              :file-list="applicationInfo.attachment"
              import-api="/common/file/upload"
              btn-text="上传文件"
              @complateSetData="completeSetData($event, 'attachment')"
              @removeFileList="removeFileList($event, 'attachment')" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
          <el-form-item label="发票票面备注" prop="remark">
            <el-input
              v-model="applicationInfo.remark"
              :height="60"
              :style="{ 'font-size': '13px', 'width': showMobilePage ? '100%' : '240px' }"
              size="small"
              type="textarea"
              placeholder="请输入"
              maxlength="500"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
          <el-form-item label="开票需求简要说明" prop="description">
            <div class="flex-center">
              <el-input
                v-model="applicationInfo.description"
                :height="60"
                :style="{ 'font-size': '13px', 'width': showMobilePage ? '100%' : '240px', 'flex-shrink': 0 }"
                size="small"
                type="textarea"
                placeholder="请输入"
                maxlength="500"
                class="width240"
              />
              <el-tooltip :open-delay="800" placement="top" effect="dark">
                <div slot="content" style="max-width: 210px">
                  <span>注意负数发票必须填报正数发票号码或者红字信息表编号</span>
                </div>
                <tipIcon is-diy style="position:relative;top:2px;margin-left:6px;"/>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <HistoryInvoice ref="historyInvoiceDrawer" @submit="onSelectHistoryInvoice"/>
  </div>
</template>
<script>
import { getDepartmentAll } from '@/api/config';
import {
  getIssueInvoiceTypes,
  getIssueInvoiceProjectList,
  getIssueOurTitleList
} from '@/api/issueInvoice';
import upAttachment from '@/components/Common/upAttachment/index';
import SectionTitle from '@/components/Title';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import HistoryInvoice from './historyInvoice';
import { cascaderSoft } from '@/utils/tools';
import { mapState } from 'vuex';
import { applyBusinessTypes } from '@/filters/status';
import mobileCreate from '@/mixins/mobileCreate';

export default {
  components: {
    upAttachment,
    HistoryInvoice,
    selectWithUserLoad,
    SectionTitle
  },
  mixins: [mobileCreate],
  model: {
    prop: 'applicationInfo',
    event: 'changeValue'
  },
  props: {
    applicationInfo: {
      type: Object,
      default: () => ({})
    },
    defaultProposerList: {
      type: Array,
      default: () => []
    },
    defaultCustomerList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      clientName: '',
      deptList: [],
      invoiceProjectList: [], // 开票项目列表
      ourTitleList: [
        { id: 0, label: '厦门飞博共创网络科技股份有限公司' },
        { id: 1, label: '厦门萌力星球网络有限公司' },
        { id: 2, label: '厦门飞博文创网络有限公司' },
        { id: 3, label: '光氧聚合（厦门）文化创意有限公司' }
      ], // 我方抬头列表
      proposerListLoading: false,
      clientListLoading: false,
      defaultProposer: [], // 默认申请人-当前用户
      defaultTaxpayer: [], // 填入纳税人
      currSelectHistoryData: {
        referenceId: '',
        referenceApprovalNo: ''
      }, // 选中的引用历史
      customerList: {
        items: [],
        total: 0,
        page: 1,
        perPage: 20,
        isInit: true
      },
      rules: {
        'proposerId': [{ required: true, message: '请选择申请人', trigger: 'change' }],
        'applyDepartmentId': [{ required: true, message: '请选择申请部门', trigger: 'change' }],
        'ourTitle': [{ required: true, message: '请选择我方抬头', trigger: 'change' }],
        'invoiceType': [{ required: true, message: '请选择发票类型', trigger: 'change' }],
        'taxpayerId': [{ required: true, message: '请选择客户名称', trigger: ['change', 'blur'] }],
        'email': [{ required: true, message: '请输入发票接收邮箱', trigger: 'blur' }],
        'amount': [{ required: true, message: '请输入含税金额', trigger: 'blur' }],
        'isArrival': [{ required: true, message: '请选择', trigger: 'change' }],
        'arrivalDate': [{ required: true, message: '请选择', trigger: 'change' }],
        'isExecution': [{ required: true, message: '请选择', trigger: 'change' }],
        'isSign': [{ required: true, message: '请选择', trigger: 'change' }],
        'arrivalFile': [{ required: true, message: '请上传到账证明', trigger: 'change' }],
        'project': [{ required: true, message: '请选择开票项目', trigger: 'change' }],
        'remark': [{ required: false, message: '请输入发票票面备注', trigger: 'input' }],
        'description': [{ required: true, message: '请输入开票需求简要说明', trigger: 'input' }],
        'applyBusinessType': [{ required: true, message: '请选择业务类型', trigger: 'change' }]
      },
      applyBusinessTypes
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    invoiceTypes() {
      // 发票类型列表
      const ourTitle = this.applicationInfo.ourTitle;
      const curSelect = this.ourTitleList.find(i => i.name === ourTitle);
      return curSelect ? curSelect.linkInvoiceType || [] : [];
    }
  },
  watch: {
    'applicationInfo.invoiceType': {
      handler(val) {
        // 发票类型为'增值税专用发票'时，校验必填字段需要对应调整
        this.resetValidRules(val === '增值税专用发票');
        // 当编辑或引用发票时，要判断纳税人信息是否必填
        if (this.applicationInfo && this.applicationInfo.invoiceType) {
          this.changeInvoiceType(this.applicationInfo.invoiceType);
        }
      },
      immediate: true
    }
  },
  created() {
    this.getDeptList();
    this.setDefaultProposer();
    this.queryInvoiceProjectList();
    this.queryOurTitleList();
    // this.getInvoiceTypes();
  },
  methods: {
    changeOurTitle() {
      const invoiceType = this.applicationInfo.invoiceType;
      const isExist = this.invoiceTypes.some(i => i.label === invoiceType);
      if (!isExist) {
        this.$set(this.applicationInfo, 'invoiceType', '');
      }
    },
    changeInvoiceType(val) {
      const temp = this.invoiceTypes.filter(item => {
        return item.name === val;
      });
      this.$set(this.applicationInfo, 'invoiceRequired', temp[0].isRequired);
    },
    resetValidRules(val) {
      const dynamicAttrs = ['accountsBank', 'issueAddress', 'accountNum', 'phone'];
      dynamicAttrs.forEach(key => {
        const currRule = this.rules[key] || [{}];
        currRule[0].required = !!val;
      });
    },
    // 提供给父组件来验证完整性
    validateForm(validate = true, index = 0) {
      return new Promise((resolve, reject) => {
        if (validate) {
          this.$refs['applicationInfoForm'].validate(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject(index);
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    resetFormValidate() {
      this.$refs['applicationInfoForm'].resetFields();
    },
    // 获取部门
    getDeptList(sort = false) {
      getDepartmentAll().then(res => {
        this.deptList = (res && res.data) || [];
        if (sort) cascaderSoft(this.applicationInfo.department, this.deptList);
      });
    },
    // 发票类型
    getInvoiceTypes() {
      getIssueInvoiceTypes().then(res => {
        if (res.code === 200) {
          const result = res.data || [];
          result.forEach(item => {
            item.value = item.id;
            item.label = item.name;
            item.isStringVal = true;
            item.name = '发票类型';
          });
          this.invoiceTypes = result;
        }
      });
    },
    // 开票项目
    queryInvoiceProjectList() {
      getIssueInvoiceProjectList().then(res => {
        if (res.code === 200) {
          const result = res.data || [];
          result.forEach(item => {
            item.value = item.id;
            item.label = item.name;
            item.isStringVal = true;
            item.name = '开票项目';
          });
          this.invoiceProjectList = result;
        }
      });
    },
    // 我方抬头
    queryOurTitleList() {
      getIssueOurTitleList().then(res => {
        if (res.code === 200) {
          const result = res.data || [];
          result.forEach(item => {
            item.value = item.id;
            item.label = item.name;
            item.isStringVal = true;
            item.linkInvoiceType = item.linkInvoiceType;
          });
          this.ourTitleList = result;
        }
      });
    },
    // 选中历史发票
    onSelectHistoryInvoice(data) {
      this.currSelectHistoryData = data;
      this.$emit('onSelectHistoryInvoice', data);
    },
    handleProposerChange(data) {
      if (!data) return;
      this.applicationInfo.proposer = data.userName;
    },
    setHistoryInvoice() {
      if (this.currSelectHistoryData.referenceId) {
        const { referenceId, referenceApprovalNo } = this.currSelectHistoryData;
        this.applicationInfo.referenceId = referenceId;
        this.applicationInfo.referenceApprovalNo = referenceApprovalNo;
      }
    },
    completeSetData({ data, fileName }, key) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.applicationInfo[key]) {
        this.applicationInfo[key].push(fileList);
      } else {
        this.$set(this.applicationInfo, key, [fileList]);
      }
    },
    removeFileList({ file, index }, key) {
      this.applicationInfo[key].splice(index, 1);
    },
    setDefaultProposer() {
      this.defaultProposer = [{ id: this.userInfo.id, userName: this.userInfo.userName }];
      this.applicationInfo.proposerId = this.userInfo.id;
      this.applicationInfo.proposer = this.userInfo.userName;
      if (this.userInfo.deptName && this.userInfo.deptName.length > 0) {
        const applyDepartmentId = this.getFirstDepartment(this.userInfo.departmentAry);
        this.applicationInfo.applyDepartmentId = applyDepartmentId;
      }
      this.applicationInfo.email = this.applicationInfo.email ? this.applicationInfo.email : this.userInfo.email;
    },
    // 获取用户第一个部门的第一个子级部门
    getFirstDepartment(list) {
      if (Array.isArray(list) && list.length) {
        const deptIdArr = list[0].id;
        if (Array.isArray(deptIdArr) && deptIdArr.length) {
          return deptIdArr[deptIdArr.length - 1];
        } else {
          return null;
        }
      } else {
        return null;
      }
    },
    numInputChange(text, prop) {
      let str;
      if (prop === 'amount') {
        str = text.replace(/[^\-?\d.]/g, ''); // 允许正负数字
      } else {
        str = text.replace(/[^\d.]/g, ''); // 只允许数字
      }
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(\-?\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后3位
      this.applicationInfo[prop] = str;
    },
    // 用于手动触发表单验证
    triggerFormValidate() {
      this.$refs['applicationInfoForm'].validate();
    },
    onHistoryInvoiceDrawerShow() {
      this.$refs['customInputRef'].blur();
      this.$refs['historyInvoiceDrawer'].openDrawer();
      const { referenceId } = this.applicationInfo;
      referenceId && (this.$refs['historyInvoiceDrawer'].referenceId = referenceId);
    }
  }
};
</script>
<style lang="scss" scoped>
.response-el-row {
  & ::v-deep {
    .el-input__inner {
      height: 32px;
      line-height: 32px;
      width: 240px;
    }
    .el-form-item__content {
      width: 240px;
    }
    .el-input__icon {
      line-height: 32px;
    }
    .el-form-item {
      margin-bottom: 24px;
    }
    .el-select {
      .el-input {
        .el-select__caret {
          color: #333333;
        }
      }
    }
  }
  .custom-input {
    ::v-deep .el-input__inner {
      cursor: pointer;
    }
    &-icon {
      font-size: 14px;
      color: #666;
      margin-right: 5px;
    }
  }
}
.loading-container {
  width: 100%;
  text-align: center;
  i {
    color: #999;
  }
}
::v-deep .indentation-form-item {
  .el-form-item {
    label {
      line-height: 1.2 !important;
    }
  }
}
</style>
